package com.yunhai.xc.common.ftp;

import java.util.Properties;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
 * ftp 上传控制器
 * @author zgf
 * @see http://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html
 */
public class Ftp {
	Session session = null;
	Channel channel = null;
	String sftp_req_host = "123.249.94.102";
	String sftp_req_username = "root";
	String sftp_req_password = "jing428@520!";
	int sftp_port = 22;
	String dst = "/opt/temp/upload/image";
	private static final Logger LOG = Logger.getLogger(Ftp.class.getName());

	public ChannelSftp getChannel() throws JSchException {
		JSch jsch = new JSch(); // 创建JSch对象
		session = jsch.getSession(sftp_req_username, sftp_req_host, sftp_port); // 根据用户名，主机ip，端口获取一个Session对象
		if (sftp_req_password != null) {
			session.setPassword(sftp_req_password); // 设置密码
		}
		Properties config = new Properties();
		config.put("StrictHostKeyChecking", "no");
		session.setConfig(config); // 为Session对象设置properties
		session.setTimeout(6000); // 设置timeout时间
		session.connect(); // 通过Session建立链接
		channel = session.openChannel("sftp"); // 打开SFTP通道
		channel.connect(); // 建立SFTP通道的连接
		LOG.debug("Connected successfully to ftpHost = " + sftp_req_host + ",as ftpUserName = " + sftp_req_username
				+ ", returning: " + channel);
		return (ChannelSftp) channel;
	}

	public void closeChannel() throws Exception {
		if (channel != null) {
			channel.disconnect();
		}
		if (session != null) {
			session.disconnect();
		}
	}

	public void upload(String filename) throws Exception {
		Ftp channel = FtpSingleton.getInstance();
		ChannelSftp chSftp = channel.getChannel();
		chSftp.put(filename, dst, ChannelSftp.OVERWRITE);
		// chSftp.put(in, filename, ChannelSftp.OVERWRITE);
		chSftp.quit();
		channel.closeChannel();
	}

	public static void main(String[] args) throws Exception {

		// String filename = "E:\\opt\\temp\\upload\\12\\20170821\\6.png"; //
		// 本地文件名
		// FtpSingleton.getInstance().upload(new FileInputStream(new
		// File(filename)), "1236");
	}
}
